package x.ovo.wechat.bot.http.request.contact;

import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import x.ovo.wechat.bot.common.Constant;
import x.ovo.wechat.bot.common.entity.BatchContactQuery;
import x.ovo.wechat.bot.common.entity.Contact;
import x.ovo.wechat.bot.common.http.request.ApiRequest;
import x.ovo.wechat.bot.common.http.session.LoginSession;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

public class BatchContactRequest extends ApiRequest<List<Contact>> {

    private final List<BatchContactQuery> queryList;

    /**
     * 构造函数，初始化API请求的默认参数。
     */
    public BatchContactRequest(LoginSession session, List<BatchContactQuery> queryList) {
        super(session);
        this.queryList = queryList;
    }

    @Override
    public String getUrl() {
        return UrlBuilder.of(this.session.getUrl())
                .addPath(Constant.BATCH_GET_CONTACT)
                .addQuery("r", System.currentTimeMillis())
                .addQuery("pass_ticket", this.session.getPassTicket())
                .addQuery("type", "ex")
                .build();
    }

    @Override
    public String getMethod() {
        return "POST";
    }

    @Override
    public boolean isJson() {
        return true;
    }

    @Override
    public Map<String, Object> getParameters() {
        return Map.of("BaseRequest", this.baseRequest, "Count", this.queryList.size(), "List", this.queryList);
    }

    @Override
    public Function<String, List<Contact>> responseHandler() {
        return s -> {
            JSONObject object = JSONUtil.parseObj(s);
            if (object.getJSONObject("BaseResponse").getInt("Ret") == 0) {
                return object.getJSONArray("ContactList").toList(Contact.class);
            }
            return Collections.emptyList();
        };
    }
}
